package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private HttpClientUtil httpClientUtil;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(UserLoginDTO userLoginDTO) {
        //1.获取授权码
        Map<String, String> parmMap = new HashMap<>();
        parmMap.put("appid", weChatProperties.getAppid());
        parmMap.put("secret", weChatProperties.getSecret());
        parmMap.put("js_code", userLoginDTO.getCode());
        parmMap.put("grant_type", "authorization_code");
        //2.发送给微信服务器，获取access_token
        String access_token = httpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", parmMap);
        log.info("微信返回的json字符串：{}", access_token);
        //3.解析微信返回的json字符串
        JSONObject jsonObject = JSON.parseObject(access_token);
        String openid = (String) jsonObject.get("openid");
        if (openid == null) {
            log.error("获取openid失败，微信返回的json字符串：{}", access_token);
            throw new RuntimeException("用户未登录");
        }
        //4.判断是否为新用户
        User user = userMapper.selectByOpenid(openid);

        if (user == null){
            user = new User();
            user.setName(openid.substring(0, 6));
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        //5.如果不是新用户直接返回用户信息
        return user;
    }
}
